import { director, macro, sys, view } from "cc";
import { App } from "../App";
import { EventConst, HotUpdateState, Matrix, Singleton } from "./Common"

const MAX_COUNT:number = 2;
class download extends Matrix{
    private _mod:string = '';
    constructor(name:string){
        super();
        this._mod = name;
    }
    
    public start(){

    }

    protected onDestroy(): void {
        
    }
}
export default class NativeManager extends Singleton<NativeManager>{
    private _isLandscape:boolean = true;
    private _nativeCall:Map<string,(data?:any)=>void> = null;
    private _updateList:Map<string,download> = null;
    protected onInit(...param: any[]): void {
        this._nativeCall = new Map<string,(data?:any)=>void>();
        this._updateList = new Map<string,download>();
        // native 层回调
        director.on(EventConst.App_NATIVE_MESSAGE,(flag:string,data?:any)=>{
            const call = this._nativeCall.get(flag);
            if (call){
                call(data);
                this._nativeCall.delete(flag);
            }
            App.Event.emit(flag,data);
        },this);

        App.Event.on(EventConst.FINISH_MODULE,(name:string)=>{
            this._updateList.delete(name);
        },this);
    }

    /**
     * callNative
     * 
    **/
    public callNative(flag:string,data?:string|any,call?:(data?:any)=>void) {
        
    }

    /**
     * update
        module:string     
    */
    public update(module:string) {
        if (!sys.isNative){
            App.Event.emit(EventConst.HOT_UPDATE_MODULE,module,HotUpdateState.Skip);
            return ;
        }
        if (this._updateList.has(module)) return ;
        const obj:download = this._updateList.get(module);

        const tmpObj:download = new download(module);
        if (this._updateList.size > MAX_COUNT){
            this._updateList.set(module,tmpObj);
            return ;
        }

        this._updateList.set(module,tmpObj);
        tmpObj.start();
    }

    public setOrientation(isLandscape:boolean){
        if (this._isLandscape === isLandscape) return ;
        if (sys.isNative){
            this.callNative('orientation',{landscape:isLandscape});
        } else {
            const values = isLandscape ? macro.ORIENTATION_LANDSCAPE : macro.ORIENTATION_PORTRAIT;
            view.setOrientation(values);
            setTimeout(() => {
                this._isLandscape = isLandscape;
                App.Event.emit(EventConst.RESIZE_VIEWPORT);
            }, 100);
        }
    }

}